// import Router from 'vue-router'
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // get token from cookie
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist
// const router = new Router({
//   routes: constantRoutes
// })
let routesAdded = false // 标记是否已添加路由
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)

  const isLoggedIn = getToken()

  if (isLoggedIn) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      // 动态生成路由
      // const hasRoutes = store.getters.routes && store.getters.routes.length > 0
      if (routesAdded) {
        next()
      } else {
        try{
          const accessedRoutes = await store.dispatch('permission/generateRoutes')
          router.addRoutes(accessedRoutes)  // 添加路由
          routesAdded = true // 更新标记
          next({ ...to, replace: true }) // 确保路由已更新
        } catch (error) {
          console.error('Error during route generation or navigation:', error)
          next({ path: '/login', query: { redirect: to.path } })
        }
      //   try {
      //     console.log('Generated routes:', accessRoutes);

      //     //router.matcher = new Router().matcher // 注意: 这只适用于 Vue Router 3.x

      //     // accessRoutes.forEach(route => {
      //     //   router.addRoutes(route) // 注意: Vue Router 3.x 使用 addRoutes
      //     // })
      //     accessRoutes.forEach(route => {
      //       if (!router.options.routes.find(r => r.path === route.path)) {
      //         router.addRoutes([route])
      //       }
      //     })
      //     console.log('Routes added:', router.options.routes);
      //     next({ ...to, replace: true })
      //   } catch (error) {
      //     console.error('Error during route generation or navigation:', error)
      //     next({ path: '/login', query: { redirect: to.path } })
      //   } finally {
      //     NProgress.done()
      //   }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
